package com.yuyou.fn.common.util;

import com.github.wens.mybatisplus.plugins.Page;
import com.github.wens.mybatisplus.toolkit.IdWorker;
import com.sun.tools.hat.internal.util.Comparer;
import net.sourceforge.pinyin4j.PinyinHelper;
import net.sourceforge.pinyin4j.format.HanyuPinyinCaseType;
import net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat;
import net.sourceforge.pinyin4j.format.HanyuPinyinToneType;
import net.sourceforge.pinyin4j.format.exception.BadHanyuPinyinOutputFormatCombination;
import org.apache.commons.lang3.StringUtils;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.PrintStream;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Array;
import java.math.BigDecimal;
import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.URLEncoder;
import java.nio.charset.Charset;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created by wens on 16/10/20.
 */
public class Utils {

    public static  Double roundByDouble(Double d,int num){
        if (d==null || num<0){
            return 0d;
        }

        BigDecimal format   =   new   BigDecimal(d);
        Double result= format.setScale(num,   BigDecimal.ROUND_HALF_UP).doubleValue();
        return result;
    }

    public static  Boolean checkListNotEmpty(List list){
        if (list==null || list.size()<=0){
            return false;
        }else {
            return true;
        }
    }

    public static  Boolean checkListEmpty(List list){
        if (list==null || list.size()<=0){
            return true;
        }else {
            return false;
        }
    }

    public static List<Long> toLongIds(String idsStr) {

        if (StringUtils.isEmpty(idsStr)) {
            return Collections.EMPTY_LIST;
        }

        String[] idsArr = idsStr.split(",");
        if (idsArr.length == 0) {
            return Collections.emptyList();
        }
        List<Long> ids = new ArrayList<>();
        for (String c : idsArr) {
            ids.add(Long.valueOf(c.trim()));
        }
        return ids;
    }

    public static List<Long> toArrayLongIds(String idsStr) {

        if (StringUtils.isEmpty(idsStr)) {
            return new ArrayList<>();
        }

        String[] idsArr = idsStr.split(",");
        if (idsArr.length == 0) {
            return  new ArrayList<>()  ;
        }
        List<Long> ids = new ArrayList<>();
        for (String c : idsArr) {
            ids.add(Long.valueOf(c.trim()));
        }
        return ids;
    }

    public static byte[] s2b(String string) {
        return string == null ? null : string.getBytes(Charset.forName("UTF8"));
    }

    public static String b2s(byte[] bytes) {
        return bytes == null ? null : new String(bytes, Charset.forName("UTF8"));
    }

    public static byte[] l2b(Long along) {
        return s2b(String.valueOf(along));
    }

    public static Long b2l(byte[] bytes) {
        String string = b2s(bytes);
        return string == null ? null : Long.parseLong(string);
    }

    public static String leftPaddingZero(Long number, int len) {
        StringBuilder sb = new StringBuilder();
        sb.append(number);
        while (sb.length() < len) {
            sb.insert(0, "0");
        }
        return sb.toString();
    }


    public static String formatDate(Date date, String pattern) {
        if (date==null){
            return "";
        }
        return new SimpleDateFormat(pattern).format(date);
    }


    private static String[] chineseOfWeek = {"日", "一", "二", "三", "四", "五", "六"};

    public static String formatTwoDateDefault(Date dateStart, Date dateEnd) {

        SimpleDateFormat dateFormat = new SimpleDateFormat("MM/dd");
        SimpleDateFormat timeFormat = new SimpleDateFormat("HH:mm");


        String d1 = dateFormat.format(dateStart);
        String d2 = dateEnd == null ? "" : dateFormat.format(dateEnd);

        String t1 = timeFormat.format(dateStart);
        String t2 = dateEnd == null ? "" : timeFormat.format(dateEnd);

        StringBuilder sb = new StringBuilder(50);
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(dateStart);

        if (d1.equals(d2)) {
            sb.append(d1).append("(周").append(chineseOfWeek[calendar.get(Calendar.DAY_OF_WEEK) - 1]).append(")").append(t1).append("-").append(t2);
        } else {
            sb.append(d1).append("(周").append(chineseOfWeek[calendar.get(Calendar.DAY_OF_WEEK) - 1]).append(")").append(t1);
            if (dateEnd != null) {
                calendar.setTime(dateEnd);
                sb.append("-").append(d2).append("(周").append(chineseOfWeek[calendar.get(Calendar.DAY_OF_WEEK) - 1]).append(")").append(t2);
            }

        }
        return sb.toString();
    }


    public static String formatFileSize(int size) {
        return size < 1024 ? String.valueOf(size) : size / 1024 < 1024 ? String.format("%dK", size / 1024) : String.format("%dM", size / 1024 / 1024);
    }

    public static int length(Object value) {
        if (value == null) {
            return 0;
        }
        if (value instanceof Collection) {
            return ((Collection) value).size();
        } else if (value.getClass().isArray()) {
            return Array.getLength(value);
        } else if (value instanceof Map) {
            return ((Map) value).size();
        } else if (value instanceof String) {
            return ((String) value).length();
        } else {
            throw new UnsupportedOperationException("Can not get length for the object : " + value);
        }
    }

    public static long percent(long a, long b) {

        if (a == 0 || b == 0) {
            return 0;
        }
        return (long) (100.00 * a / b);
    }

    public static String urlEncode(String srcUrl) throws UnsupportedEncodingException {
        return URLEncoder.encode(srcUrl, "utf-8");
    }

    public static String camelCase(String src ){
        /*
		 * 处理下划线分割命名字段
		 */
        StringBuffer sb = new StringBuffer(src.length());
        String[] fields = src.split("_");
        sb.append(fields[0].toLowerCase());
        for (int i = 1; i < fields.length; i++) {
            String temp = fields[i];
            sb.append(temp.substring(0, 1).toUpperCase());
            sb.append(temp.substring(1).toLowerCase());
        }
        return sb.toString();
    }

    final static  char[] codeCharSet  = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ".toCharArray() ;

    public static String to62(long number){
        long rest=number;
        Stack<Character> stack=new Stack<Character>();
        StringBuilder result=new StringBuilder(20);
        while(rest!=0){
            stack.add(codeCharSet[(int)(rest-(rest/62)*62)]);
            rest=rest/62;
        }
        for(;!stack.isEmpty();){
            result.append(stack.pop());
        }
        return result.toString();

    }

    public static Date parseDate(String date, String format) {
        try {
            return new SimpleDateFormat(format).parse(date);
        } catch (ParseException e) {
            throw new RuntimeException(e);
        }
    }

    public static <T> Page<T> newPage(Page<?> page) {
        Page nPage  = new Page<T>(page.getCurrent(),page.getSize());
        nPage.setTotal(page.getTotal());
        return nPage;
    }

    public static boolean isEmpty(Collection<?> c ){
        return c == null || c.isEmpty() ?  true : false ;
    }


    public static int parseInt(String src){
        if(src == null ){
            src  = "0";
        }
        return Integer.parseInt(src);
    }

    public static <T> List<T> unique(List<T> list){
        return new ArrayList<>(new HashSet<T>(list));
    }

    public static String getExceptionStackTrace(Exception e) {
        ByteArrayOutputStream out = new ByteArrayOutputStream(500 );
        try{
            e.printStackTrace(new PrintStream(out));
            out.flush();
        }catch (Exception ex){
            try {
                out.write("Get exception stack trace fail".getBytes());
            } catch (IOException e1) {
                //ignore
            }
        }
        return out.toString();
    }

    public static String doubleToPercent(double num){
        return (double)Math.round(num*10000)/100+"%";
    }

    public static String getPercent(String molecularString ,String denominatorString,int num){
        if (StringUtils.isEmpty(molecularString) || StringUtils.isEmpty(denominatorString) ){
            return "0.00%";
        }

        BigDecimal molecular=new BigDecimal(molecularString);
        BigDecimal denominator=new BigDecimal(denominatorString);
        if(BigDecimals.compare(molecular,BigDecimal.ZERO) == 0 || BigDecimals.compare(denominator,BigDecimal.ZERO) == 0){
            return "0.00%";
        }
        BigDecimal bigDecimal=molecular.divide(denominator,10,BigDecimal.ROUND_HALF_UP);
        bigDecimal= BigDecimals.toFixed2(bigDecimal.multiply(new BigDecimal(100)),2);//BigDecimals.toFixed2(bigDecimal,num).multiply(new BigDecimal(100));
        String result=bigDecimal.toString()+"%";
        return result;
    }

    public static String formatString(Object o){
        if (o==null){
            return "0";
        }else {
            return o.toString();
        }
    }

    public static String formatPercentString(Object o){
        if (o==null || "0".equals(o.toString())){
            return "0.00%";
        }else {
            return o.toString();
        }
    }

    public  static String toPinyin(String chinese) {
        StringBuilder pybf =  new StringBuilder();
        char[] arr = chinese.toCharArray();
        HanyuPinyinOutputFormat defaultFormat =  new HanyuPinyinOutputFormat();
        defaultFormat.setCaseType(HanyuPinyinCaseType.LOWERCASE);
        defaultFormat.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
        for ( int i = 0; i < arr.length; i++) {
            if (arr[i] > 128) {
                try {
                    pybf.append(PinyinHelper.toHanyuPinyinStringArray(arr[i], defaultFormat)[0]);
                }  catch (Exception e) {
                    e.printStackTrace();
                }
            }  else {
                pybf.append(arr[i]);
            }
        }
        return pybf.toString();
    }


    public static List removeDuplicate(List list) {
        if (list==null ||list.size()<=0){
            return Collections.EMPTY_LIST;
        }
        List list1=new ArrayList();
        HashSet h = new HashSet(list);
        //list.clear();
        list1.addAll(h);
        return list1;
    }

    public static String getHostIP() {
        try {
            Enumeration<NetworkInterface> allNetInterfaces = NetworkInterface.getNetworkInterfaces();
            InetAddress ip = null;
            while (allNetInterfaces.hasMoreElements()) {
                NetworkInterface netInterface = (NetworkInterface) allNetInterfaces.nextElement();
                if (netInterface.isLoopback() || netInterface.isVirtual() || !netInterface.isUp()) {
                    continue;
                } else {
                    Enumeration<InetAddress> addresses = netInterface.getInetAddresses();
                    while (addresses.hasMoreElements()) {
                        ip = addresses.nextElement();
                        if (ip != null && ip instanceof Inet4Address) {
                            return ip.getHostAddress();
                        }
                    }
                }
            }
        } catch (Exception e) {

        }
        return "";
    }


    public static List<String> toStringList(String str) {

        if (StringUtils.isEmpty(str)) {
            return Collections.EMPTY_LIST;
        }

        String[] strArr = str.split(",");
        if (strArr.length == 0) {
            return Collections.emptyList();
        }
        List<String> list = new ArrayList<>();
        for (String c : strArr) {
            list.add(c);
        }
        return list;
    }

}
